#include <myheader.h>
#define HEADER_SIZE 1024
#define RECV_SIZE 1024
#define FILEPATH "/home/lwj/wangdao/network_program/"\
    "02_socket_communicate/dou.txt"
#define FILENAME_SIZE 20
/*Usage: use the socket and http to get the file client  */
int main(int argc, char *argv[])
{
    char *ip = "192.168.112.129";
    char *port = "8080";
    //create the socket_fd
    int socket_fd = socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(socket_fd,-1,"socket");
    struct sockaddr_in sock_addr;
    sock_addr.sin_family = AF_INET;
    sock_addr.sin_addr.s_addr = inet_addr(ip);
    sock_addr.sin_port = htons(atoi(port));

    //create the http string the url is in the 
    const char *str1 = "GET /";
    const char *str2 = " HTTP/1.1\r\n"
        "Host: example.com\r\n"
        "Connection: keep-alive\r\n"
        "\r\n";
    char header[HEADER_SIZE];
    memset(header,0,sizeof(header));
    sprintf(header,"%s%s%s",str1,FILEPATH,str2);

    //get the file name
    char file_name[FILENAME_SIZE] = {0};
    char *tail = strstr(header," HTTP/1.1");
    char *head = tail;
    while(*head != '/'){
        head --;
    }
    head++;
    for(int i = 0 ;head != tail; head++, i++){
        file_name[i] = *head;
    }


    //connect;
    int ret = connect(socket_fd,(struct sockaddr*)&sock_addr,
                      sizeof(sock_addr));
    ERROR_CHECK(ret,-1,"connect");
    //send the message
    ret = send(socket_fd,header,strlen(header),0);
    ERROR_CHECK(ret,-1,"send");

    //recv
    char buf[RECV_SIZE]= {0};
    memset(buf,0,sizeof(buf));
    int file_fd = open(file_name,O_WRONLY | O_CREAT, 0666);
    ERROR_CHECK(ret,-1,"open");
    int recv_cnt;
    while((recv_cnt = recv(socket_fd,buf,sizeof(buf),0)) > 0){
        int write_cnt = write(file_fd,buf,sizeof(buf));
        ERROR_CHECK(write_cnt,-1,"write");
        memset(buf,0,sizeof(buf));
    }
    return 0;
}

